package com.zsk.sso.config.listener;

import java.util.List;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.springframework.stereotype.Component;

import com.zsk.sso.util.HttpUtil;
import com.zsk.sso.util.MockDbUtil;
import com.zsk.sso.vo.ClientInfoVo;

/**
 * 监听session,用于退出所有客户端
 * 
 * @author keke
 * @date 2020/09/27
 */
@WebListener
@Component
public class SessionListener implements HttpSessionListener {

    @Override
    public void sessionCreated(HttpSessionEvent se) {

    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        HttpSession session = se.getSession();
        String token = (String)session.getAttribute("token");
        if (token == null)
            return;
        // 删除t_token表中的数据
        MockDbUtil.removeToken(token);
        List<ClientInfoVo> clientInfoVoList = MockDbUtil.DB_CLIENT_INFO.remove(token);
        try {
            if (clientInfoVoList != null) {
                for (ClientInfoVo vo : clientInfoVoList) {
                    System.out.println("sso 注销：" + vo.getClientUrl());
                    // 获取出注册的子系统,依次调用子系统的登出的方法
                    HttpUtil.sendHttpRequest(vo.getClientUrl(), vo.getJsessionid());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
